package com.egreen.admin.service.api;

import com.egreen.admin.common.exception.JwtFormatException;
import com.egreen.admin.common.exception.JwtNotFoundException;
import com.egreen.common.serviceapi.admin.IAdminCheckJwtApi;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

@DubboService

public class JwtCheckAdminApi implements IAdminCheckJwtApi {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * redis存储的前缀
     */
    private static String KEY_CODE = "token:admin:";
    /**
     * 签名
     */
    private static String APP_SECRET = "e-GreenRecycling-Admin";

    @Override
    public Object checkAdminJwt(String jwtToken) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        if (claimsJws == null) {
            throw new JwtFormatException();
        }

        Object userId = claimsJws.getBody().get("adminId");
        String key = KEY_CODE + userId;
        //若redis中不存在该记录则抛出异常
        if (!redisTemplate.hasKey(key)) {
            throw new JwtNotFoundException();
        }
        return claimsJws.getBody();
    }

}
